<template>
  <div class="lg_0_container" style="background-color: #1a7ddf">
    <img style="position: absolute; top: 18px; left: 45px" src="../../assets/back/logo.png" />
    <el-row style="height: 100%; width: 100%" class="my-10" align="middle" justify="center">
      <el-col :span="22" style="max-width: 900px; height: 566px; display: flex">
        <el-col :span="14" class="login-left-bg">
          <div class="span-content">
            以标准化的共础数据，实现信息联动和共享，实现全过程数字化管理。系统通过硬件设备采集实名制及考勒信息，确保信息的准确率和采集效率，实现数字信息化管理，方便管理人员及时查看与跟进。
          </div>
        </el-col>
        <el-col :span="14" class="login_right" style="margin-left: -3px">
          <div class="login-container">
            <el-form
              ref="loginFormRef"
              style="height: 566px; border-top-right-radius: 20px; border-bottom-right-radius: 20px; padding-left: 50px"
              :model="loginData"
              :rules="loginRules"
              class="login-form"
            >
              <el-row :gutter="24" style="margin-top: 30px; margin-bottom: 30px; color: #999999">
                <el-col :span="12" align="center"
                  ><span type="primary" class="tab-title tab-active">用户登录</span></el-col
                >
                <el-col :span="12" align="center"
                  ><span type="primary" class="tab-title" @click.prevent="corpregister">企业注册</span></el-col
                >
              </el-row>
              <!-- 账号 -->
              <el-row justify="center" class="form-group" :gutter="24">
                <el-col :span="20">
                  <el-form-item prop="username">
                    <el-input
                      ref="username"
                      v-model="loginData.username"
                      size="large"
                      placeholder="请输入账号"
                      name="username"
                      :prefix-icon="User"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- 密码 -->
                <el-col :span="20">
                  <el-form-item prop="password">
                    <el-input
                      v-model="loginData.password"
                      placeholder="请输入密码"
                      size="large"
                      :show-password="true"
                      name="password"
                      :prefix-icon="Lock"
                      @keyup="checkCapslock"
                      @keyup.enter="handleVerifyUserName"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- 验证码 -->
                <el-col :span="20">
                  <el-form-item prop="code">
                    <el-input
                      v-model="loginData.code"
                      name="code"
                      size="large"
                      class="code-input"
                      :prefix-icon="CircleCheck"
                      placeholder="请输入验证码"
                      @keyup.enter="handleVerifyUserName"
                    >
                      <template #append>
                        <el-image :src="captchaBase64" style="height: 30px" @click="getCaptcha" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-button
                    size="large"
                    :loading="loading"
                    type="primary"
                    round
                    class="w-full t0_login"
                    @click.prevent="handleVerifyUserName"
                    >{{ $t("login.login") }}
                  </el-button>
                </el-col>
              </el-row>
              <el-row :gutter="24" style="margin-top: 10px; margin-left: 30px; margin-right: -2px">
                <el-col :span="10"><el-link @click.prevent="projectregister"> 项目登记 </el-link> </el-col>
                <el-col :span="10" style="text-align: right" @click.prevent="forgotpassword"
                  ><el-link>忘记密码?</el-link></el-col
                >
              </el-row>
            </el-form>
            <SelectRole
              v-if="dialogSelect.visible"
              :dialog-select="dialogSelect"
              :list="select_options"
              @select-send-close="selectSendClose"
            >
            </SelectRole>
          </div>
        </el-col>
      </el-col>
    </el-row>
  </div>
  <div class="div-bottom">
    <el-row :gutter="24" style="margin: 0" align="middle" justify="center">
      <el-col style="text-align: center; line-height: 44px">
        <div>
          技术支持：西藏银行股份有限公司 西藏慧软智能科技有限公司 客服服务电话：0891-6513818 客服邮箱：SMZ@xzhr0891.com
          投诉邮箱：0891@xzhr0891.com
          <!-- 主办单位：西藏自治区住房和城乡建设厅 丨 版权所有：西藏自治区住房和城乡建设厅 丨备案号：藏ICP备07000001号-1 丨
          网站标志码：5400000029 丨 藏公网安备 54010202000233号 丨 技术支持：西藏慧软智能科技有限公司 -->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ref } from "vue";
import SelectRole from "@/views/common/SelectRole/index.vue";
import { Lock, User, CircleCheck } from "@element-plus/icons-vue";
import { getDistStore } from "@/store/modules/dict";
// 状态管理依赖
import { useUserStore } from "@/store/modules/user";

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import { getCaptchaApi, VerifyUserNameLogin } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import { getDicts } from "@/store/modules/dict";
import { isMobile } from "@/utils";

const select_options = ref([]);
const userStore = useUserStore();
const route = useRoute();
const mobile = ref(false);
const itemSpan = ref(11);

if (isMobile()) {
  mobile.value = true;
  itemSpan.value = 22;
}
/**
 * 按钮loading
 */
const loading = ref(false);

/**
 * 是否大写锁定
 */
const isCapslock = ref(false);

/**
 * 密码是否可见
 */
const passwordVisible = ref(false);

/**
 * 验证码图片Base64字符串
 */
const captchaBase64 = ref();

/**
 * 登录表单引用
 */
const loginFormRef = ref(ElForm);

const loginData = ref<LoginData>({
  username: "",
  password: "",
  usertype: 1,
  usertypeName: "",
  code: "",
  id: "",
});
getDistStore().then((resp) => {
  // select_options.value = getDicts("userType"); //登录角色
  // loginData.value.usertype = localStorage.getItem("usertype") ? Number(localStorage.getItem("usertype")) : 1;
  // loginData.value.usertypeName =
  //   select_options.value &&
  //   select_options.value[localStorage.getItem("usertype") ? parseInt(localStorage.getItem("usertype") ?? "") - 1 : 0][
  //     "label"
  //   ];
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "用户名不能为空！" }],
  password: [{ required: true, trigger: "blur", validator: passwordValidator }],
  usertype: [{ required: true, trigger: "blur" }],
  code: [{ required: true, trigger: "blur", message: "请输入验证码！" }],
};

/**
 * 密码校验器
 */
function passwordValidator(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error("密码长度不能小于6位!"));
  } else {
    callback();
  }
}

/* 关闭选择 */
function selectSendClose(info: any) {
  if (info) {
    loginData.value.usertype = info.value;
    loginData.value.usertypeName = info.label;
    handleLogin();
  }
  dialogSelect.visible = false;
}

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e;
  isCapslock.value = key && key.length === 1 && key >= "A" && key <= "Z";
}

const dialogSelect = reactive({
  visible: false,
  title: "选择登录角色",
});

function usertypeClick() {
  dialogSelect.visible = true;
}

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi(1).then((res: any) => {
    const { base64Str, id } = res.data;
    loginData.value.id = id;
    captchaBase64.value = "data:image/png;base64," + base64Str;
  });
}

function corpregister() {
  router.push({ path: "/corpregister" });
}

function constructorregister() {
  router.push({ path: "/constructorregister" });
}

function projectregister() {
  router.push({ path: "/projectregister" });
}

function forgotpassword() {
  router.push({ path: "/forgotpassword" });
}

/**
 * 登录
 */
// function handleLogin() {
//   loginFormRef.value.validate((valid: boolean) => {
//     if (valid) {
//       loading.value = true;
//       userStore
//         .login(loginData.value)
//         .then(() => {
//           const query: LocationQuery = route.query;
//           const redirect = (query.redirect as LocationQueryValue) ?? "/";
//           const otherQueryParams = Object.keys(query).reduce(
//             (acc: any, cur: string) => {
//               if (cur !== "redirect") {
//                 acc[cur] = query[cur];
//               }
//               return acc;
//             },
//             {}
//           );
//           router.push({ path: redirect, query: otherQueryParams });
//         })
//         .catch(() => {
//           // 验证失败，重新生成验证码
//           getCaptcha();
//         })
//         .finally(() => {
//           loading.value = false;
//         });
//     }
//   });
// }
const handleVerifyUserName = () => {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;

      VerifyUserNameLogin(loginData.value.username, loginData.value.password)
        .then((res: any) => {
          if (res.success) {
            if (res.data.length > 1) {
              select_options.value = res.data;
              usertypeClick();
              return;
            } else if (res.data.length == 1) {
              loginData.value.usertype = res.data[0].value;
              loginData.value.usertypeName = res.data[0].label;
              handleLogin();
              return;
            } else if (res.data.length == 0) {
              ElMessageBox.alert("账号或密码错误", "提示", {
                type: "error",
              });
            }
            loading.value = false;
          } else {
            loading.value = false;
          }
        })
        .catch((err) => {
          loading.value = false;
          ElMessage.error(err || "登录失败");
        });
    }
  });
};
const handleLogin = useThrottleFn(() => {
  loading.value = true;
  userStore
    .login(loginData.value)
    .then((actionCode) => {

      console.log("loginlogin", new Date().getTime());
      if (actionCode == 2) {
        ElMessageBox.confirm("存在审核失败的项目，是否跳转修改", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (loginData.value.usertype == 2)
            router.push({ path: "/corp/project/projectInfo" }).then(() => {
              loading.value = false;
            });
          if (loginData.value.usertype == 5)
            router.push({ path: "/manager/project/projectInfo" }).then(() => {
              loading.value = false;
            });
        });
        return;
      }
      if (actionCode != 0) return;
      debugger;
      let query: LocationQuery = route.query;
      const redirect = (query.redirect as LocationQueryValue) ?? "/";
      const otherQueryParams = Object.keys(query).reduce((acc: any, cur: string) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});

      console.log("loginlogin--router", new Date().getTime());
      router.push({ path: redirect, query: otherQueryParams }).then(() => {
        loading.value = false;
      });
    })
    .catch((error) => {
      // 验证失败，重新生成验证码
      setTimeout(() => {
        getCaptcha();
      }, 1000);
      loading.value = false;
    })
    .finally(() => {});
}, 3000);

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.div-bottom {
  height: 5%;
  background-color: #3b4255;
  color: #ffffff;
  font-family: "微软雅黑", sans-serif;
}

.login-left-bg {
  background-image: url("../../assets/back/login-bg-1.png");
  // width: 531px;
  height: 567px;
}

.font17 {
  font-size: 18px !important;
}

.span-content {
  text-indent: 2em;
  color: #e4f0fe;
  font-family: "微软雅黑", sans-serif;
  margin-top: 43px;
  margin-left: 50px;
  margin-right: 50px;
  line-height: 32px;
}

.lg_0_container {
  background-size: cover;
  background-image: url("../../assets/back/login-bg.png");
  width: 100%;
  height: 95%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.reg_row {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.tab-title {
  font-size: 25px;
  cursor: pointer;
  letter-spacing: 1px;
  font-family: "Microsoft JhengHei";
  font-weight: 600;
}
.tab-title:hover {
  border-bottom: 2px solid;
  color: #79bbff;
}

.tab-active {
  border-bottom: 2px solid;
  color: #79bbff;
}

.login-container {
  // width: 100%;
  min-height: 100%;
  overflow: hidden;
  //background-color: #003375;

  .title-wrap {
    filter: contrast(30);

    .title {
      letter-spacing: 4px;
      animation: showup 3s forwards;
    }

    @keyframes showup {
      0% {
        letter-spacing: -20px;
      }

      100% {
        letter-spacing: 4px;
      }
    }
  }

  .login-form {
    width: 520px;
    max-width: 100%;
    //padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    //border: 1px solid red;
    background: #ffffff;
    padding: 15px 30px;
    // box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.9);

    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      img {
        width: 120px;
        height: 48px;
        cursor: pointer;
      }
    }
  }
}
:deep(.el-input-group__prepend) {
  background-color: var(--el-fill-color-blank);
}
:deep(.el-input-group__append) {
  background-color: var(--el-fill-color-blank);
}
:deep(.el-input__wrapper) {
  border-radius: 25px;
}
:deep(.code-input .el-input__wrapper) {
  border-radius: 25px 0px 0px 25px;
}
:deep(.code-input .el-input-group__append) {
  padding: 0px 10px 0px 0px;
  border-radius: 0px 25px 25px 0px;
}
:deep(.form-group .el-col) {
  padding-top: 15px;
}
:deep(.el-form-item__error) {
  margin-left: 38px;
}

.form-group {
  margin-top: 50px;
}
</style>
